package com.yyfax.ph.home.imageupload;

import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.Constants;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import rx.Subscriber;

import java.io.File;
import java.util.List;
import java.util.Map;

public class UploadImagePresenter extends Presenter<UploadImageModel, UploadImagePresenter.View> {

	public static final String TAG = UploadImagePresenter.class.getSimpleName();
	private static final String UPLOAD_IMAGE_FAILED = "图片上传失败!";
	private static final String CONNECT_NETWORK_FAILED = "连接网络失败，请检查网络设置!";

	public interface View extends IView {

		void onUploadImage(String filePath, String fileName, String imageId);

		void onUploadImageFailure(String filePath, String tips);

		void onUploadImageCancel(String filePath, String tips);
	}

	public static class Generator implements PresenterFactory<UploadImagePresenter> {
		@Override
		public UploadImagePresenter create() {
			return new UploadImagePresenter();
		}
	}

	private View mView;
	private String mRequestPage;

	@Override
	public void attach(View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new UploadImageModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public void uploadImage(final String filePath, String imageType) {
		if (TextUtils.isEmpty(filePath)) {
			mView.onUploadImageFailure(filePath, UPLOAD_IMAGE_FAILED);
			return;
		}
		File file = new File(filePath);
		if (!file.exists()) {
			mView.onUploadImageFailure(filePath, UPLOAD_IMAGE_FAILED);
			return;
		}
		final RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
		MultipartBody.Part part = MultipartBody.Part.createFormData("files", file.getName(), requestBody);
		RequestBody type = RequestBody.create(MediaType.parse("text/plain"), imageType);
		UploadImageModel.UploadImage entity = new UploadImageModel.UploadImage(part, type);
		if (!Constants.isConnected) {//如果没有网络
			UploadImageModel.UploadFailure result = new UploadImageModel.UploadFailure();
			result.filePath = filePath;
			result.requestPage = mRequestPage;
			result.tips = CONNECT_NETWORK_FAILED;
			EventAgent.post(result);
			return;
		}
		//noinspection unchecked
		mModel.execute(entity, FUNCTIONAL_CODE, filePath, mRequestPage)
				.compose(mBaseView.composeLifecycle())//销毁Presenter前停止上传
				.subscribe(new Subscriber<BaseResultEntity>() {
					private boolean success = false;

					@Override
					public void onStart() {
						CLog.d(TAG, "new Subscriber: onStart");
					}

					@Override
					public void onNext(final BaseResultEntity result) {
						success = true;
						CLog.d(TAG, "new Subscriber: onNext filePath=" + filePath);
						result.extraParam = filePath;
						result.requestPage = mRequestPage;
						EventAgent.post(result);
					}

					@Override
					public void onCompleted() {
						CLog.d(TAG, "new Subscriber: onCompleted filePath=" + filePath);
						CLog.d(TAG, "new Subscriber: onCompleted success=" + success);
						if (!success) {
							UploadImageModel.UploadCancel result = new UploadImageModel.UploadCancel();
							result.filePath = filePath;
							result.requestPage = mRequestPage;
							result.tips = UPLOAD_IMAGE_FAILED;
							EventAgent.post(result);
						}
						unsubscribe();
					}

					@Override
					public void onError(Throwable e) {
						CLog.d(TAG, "new Subscriber: onError");
						UploadImageModel.UploadFailure result = new UploadImageModel.UploadFailure();
						result.filePath = filePath;
						result.requestPage = mRequestPage;
						result.tips = UPLOAD_IMAGE_FAILED;
						EventAgent.post(result);
						unsubscribe();
					}
				});
	}

	public void uploadImages(List<String> fileList, String imageType) {
		if (null != fileList && fileList.size() > 0) {
			uploadImage(fileList.get(0), imageType);
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadResult(UploadImageModel.UploadResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			String filePath = (String) result.extraParam;
			String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
			if (isResponseSuccess(result)) {
				Map<String, String> uploadResult = result.getContent();
				mView.onUploadImage(filePath, fileName, uploadResult.get(fileName));
			} else {
				String msg = TextUtils.isEmpty(result.getMsg()) ? UPLOAD_IMAGE_FAILED : result.getMsg();
				mView.onUploadImageFailure(filePath, msg);
			}
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadFailure(UploadImageModel.UploadFailure result) {
		if (mRequestPage.equals(result.requestPage)) {
			String filePath = result.filePath;
			mView.onUploadImageFailure(filePath, result.tips);
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadCancel(UploadImageModel.UploadCancel result) {
		if (mRequestPage.equals(result.requestPage)) {
			String filePath = result.filePath;
			mView.onUploadImageCancel(filePath, result.tips);
		}
	}
}
